package com.afdor.rws.event.channel.aliyun.mq.topic;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.channel.aliyun.mq.AbstractAliyunEventConsumer;
import com.afdor.rws.event.channel.aliyun.mq.utils.AliyunMQUtils;
import com.afdor.rws.event.channel.client.consumer.EventConsumer;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.SubscriptionMeta;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * 基于阿里云MQ发布订阅模式的事件消费者实现
 *
 * @author 悭梵
 * @date Created in 2018-08-15 16:25
 */
@Slf4j
@ToString
@EqualsAndHashCode
@Extension(value = "amq_topic", order = Extension.NORMAL_ORDER - 50, scope = Extension.Scope.PROTOTYPE, interfaceClass = EventConsumer.class)
public class AliyunMQTopicEventConsumer extends AbstractAliyunEventConsumer {

    @Override
    protected void doStart() {
        String queueName = AliyunMQUtils.getQueueName(getEventSourceName());
        String topicName = AliyunMQUtils.getTopicName(getEventSourceName());
        MNSClient mnsClient = getCloudAccount().getMNSClient();

        CloudTopic topic = mnsClient.getTopicRef(topicName);
        try {
            topic.create();
        } catch (Exception e) {
            log.error("创建主题异常", e);
        }

        /* 创建订阅关系关系 */
        SubscriptionMeta meta = new SubscriptionMeta();
        /* 路由队列名称 */
        meta.setSubscriptionName(queueName);
        /* 主题名称 */
        meta.setTopicName(topicName);
        /* 消息格式 */
        meta.setNotifyContentFormat(SubscriptionMeta.NotifyContentFormat.SIMPLIFIED);
        /* 接收消息的终端地址 */
        meta.setEndpoint(topic.generateQueueEndpoint(queueName));
        topic.subscribe(meta);
    }


}
